package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.RoleMapper;
import org.linlinjava.litemall.db.models.Role;
import org.linlinjava.litemall.db.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    @Override
    public Set<String> queryByIds(Integer[] roleIds) {
        Set<String> roles = new HashSet<String>();
        if(roleIds.length == 0){
            return roles;
        }
        QueryWrapper<Role> query = new QueryWrapper<>();
        query.eq("enabled", true).eq("deleted", false);
        query.in("id", Arrays.asList(roleIds));
        List<Role> roleList = this.baseMapper.selectList(query);
        for(Role role : roleList){
            roles.add(role.getName());
        }
        return roles;
    }

    @Override
    public IPage<Role> querySelective(String name, Integer pageNo, Integer pageSize) {
        Page<Role> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Role> query = new QueryWrapper<>();
        query.like(!StringUtils.isEmpty(name), "name", name);
        query.eq("enabled", true).eq("deleted", false);
        query.orderByDesc("id");
        return this.baseMapper.selectPage(page, query);
    }

    @Override
    public boolean checkExist(String name) {
        QueryWrapper<Role> query = new QueryWrapper<>();
        query.eq("deleted", false);
        query.eq("name", name);
        return this.baseMapper.selectCount(query) > 0;
    }

    @Override
    public List<Role> queryAll() {
        QueryWrapper<Role> query = new QueryWrapper<>();
        query.eq("deleted", false);
        return this.baseMapper.selectList(query);
    }
}
